package com.stone.design.mode.filter;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * 过滤器链
 *
 * @author wenpan 2023/11/17 10:04 下午
 */
public class StandardFilterChain implements FilterChain {

    /**
     * 过滤器集合
     */
    private final List<Filter> filterList = Lists.newArrayList();
    /**
     * 当前执行到的过滤器下标
     */
    private int currentIndex = 0;

    @Override
    public void doFilter(HttpRequest httpRequest) {
        // 已经执行完最后一个过滤器了，直接返回
        if (currentIndex == filterList.size()) {
            return;
        }
        // 获取当前要执行的过滤器
        Filter filter = filterList.get(currentIndex);
        // 下标自增
        currentIndex = currentIndex + 1;
        // 调用当前filter的doFilter方法
        filter.doFilter(httpRequest, this);
    }

    @Override
    public void addFilter(Filter filter) {
        // 已经添加过过滤器了
        if (filterList.contains(filter)) {
            return;
        }
        filterList.add(filter);
    }

}